package com.ruoyi.system.service.impl;

import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.system.domain.UmsCustomer;
import com.ruoyi.system.domain.params.CustomerOrderListParams;
import com.ruoyi.system.domain.vo.CustomerInfo;
import com.ruoyi.system.domain.vo.CustomerOrderList;
import com.ruoyi.system.mapper.UmsCustomerMapper;
import com.ruoyi.system.mapper.WhOrderMapper;
import com.ruoyi.system.service.CustomerService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Author: ChenHaiDong
 * @CreateTime: 2023-03-01  15:50
 * @Description: TODO 客户端接口实现
 * @Version: 1.0
 */
@Service
public class CustomerServiceImpl implements CustomerService {

    @Resource
    private UmsCustomerMapper customerMapper;
    @Resource
    private RedisCache redisCache;
    @Resource
    private WhOrderMapper whOrderMapper;

    // redis存储token的key
    public static final String USER_TOKEN_KEY = "login:token:%s";

    /**
     * 客户登录
     * @param account
     * @param password
     * @return
     */
    @Override
    public String login(String account, String password) {
        UmsCustomer umsCustomer = customerMapper.selectUmsCustomerByNameOrCode(account);
        if (umsCustomer == null) {
            throw new ServiceException("password error");
        }
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        boolean matches = passwordEncoder.matches(password, umsCustomer.getPassword());
        if (!matches) {
            throw new ServiceException("password error");
        }
        String token = UUID.randomUUID().toString().replaceAll("-","");
        redisCache.setCacheObject(String.format(USER_TOKEN_KEY,token),umsCustomer.getUserId(), 60 * 60 * 48, TimeUnit.SECONDS);
        return token;
    }

    /**
     * 根据用户id获取用户详情
     * @param userId
     * @return
     */
    @Override
    public CustomerInfo getUserInfoById(Integer userId) {
        if (userId == null) {
            return null;
        }
        UmsCustomer umsCustomer = customerMapper.selectUmsCustomerByUserId(userId);
        if (umsCustomer == null) {
            return null;
        }
        CustomerInfo info = new CustomerInfo();
        BeanUtils.copyProperties(umsCustomer,info);
        return info;
    }

    /**
     * 获取客户订单列表
     * @param params
     * @return
     */
    @Override
    public List<CustomerOrderList> findCustomerOrderList(CustomerOrderListParams params) {
        return whOrderMapper.findCustomerOrderList(params);
    }
}
